package com.writing.controller;

import com.writing.common.Result;
import com.writing.entity.WritingGoal;
import com.writing.service.WritingGoalService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 写作目标控制器
 */
@RestController
@RequestMapping("/goals")
@RequiredArgsConstructor
public class WritingGoalController {

    private final WritingGoalService writingGoalService;

    /**
     * 获取写作目标列表
     */
    @GetMapping
    public Result<List<WritingGoal>> getGoals(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        try {
            List<WritingGoal> goals = writingGoalService.getGoalsByUserId(userId);
            return Result.success("获取成功", goals);
        } catch (Exception e) {
            return Result.error("获取写作目标失败: " + e.getMessage());
        }
    }

    /**
     * 获取写作目标详情
     */
    @GetMapping("/{goalId}")
    public Result<WritingGoal> getGoal(@PathVariable Long goalId, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        try {
            WritingGoal goal = writingGoalService.getGoalById(goalId, userId);
            if (goal == null) {
                return Result.error("目标不存在或无权限访问");
            }
            return Result.success("获取成功", goal);
        } catch (Exception e) {
            return Result.error("获取写作目标失败: " + e.getMessage());
        }
    }

    /**
     * 创建写作目标
     */
    @PostMapping
    public Result<WritingGoal> createGoal(@RequestBody @Valid WritingGoal goal, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        try {
            goal.setUserId(userId);
            WritingGoal createdGoal = writingGoalService.createGoal(goal);
            return Result.success("创建成功", createdGoal);
        } catch (Exception e) {
            return Result.error("创建写作目标失败: " + e.getMessage());
        }
    }

    /**
     * 更新写作目标
     */
    @PutMapping("/{goalId}")
    public Result<WritingGoal> updateGoal(@PathVariable Long goalId,
                                         @RequestBody @Valid WritingGoal goal,
                                         HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        try {
            // 验证目标是否存在且属于当前用户
            WritingGoal existingGoal = writingGoalService.getGoalById(goalId, userId);
            if (existingGoal == null) {
                return Result.error("目标不存在或无权限访问");
            }

            goal.setId(goalId);
            goal.setUserId(userId);
            WritingGoal updatedGoal = writingGoalService.updateGoal(goal);
            return Result.success("更新成功", updatedGoal);
        } catch (Exception e) {
            return Result.error("更新写作目标失败: " + e.getMessage());
        }
    }

    /**
     * 更新目标进度
     */
    @PostMapping("/{goalId}/progress")
    public Result<WritingGoal> updateProgress(@PathVariable Long goalId,
                                             @RequestBody Map<String, Object> progressData,
                                             HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        try {
            Integer increment = (Integer) progressData.get("increment");
            String note = (String) progressData.get("note");

            if (increment == null || increment <= 0) {
                return Result.error("进度增量必须大于0");
            }

            WritingGoal updatedGoal = writingGoalService.updateProgress(goalId, userId, increment, note);
            return Result.success("进度更新成功", updatedGoal);
        } catch (Exception e) {
            return Result.error("更新进度失败: " + e.getMessage());
        }
    }

    /**
     * 删除写作目标
     */
    @DeleteMapping("/{goalId}")
    public Result<Void> deleteGoal(@PathVariable Long goalId, HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        try {
            boolean deleted = writingGoalService.deleteGoal(goalId, userId);
            if (!deleted) {
                return Result.error("目标不存在或无权限访问");
            }
            return Result.success();
        } catch (Exception e) {
            return Result.error("删除写作目标失败: " + e.getMessage());
        }
    }

    /**
     * 获取目标统计信息
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> getGoalStats(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        try {
            long activeGoals = writingGoalService.getActiveGoalsCount(userId);
            long completedGoals = writingGoalService.getCompletedGoalsCount(userId);

            Map<String, Object> stats = new HashMap<>();
            stats.put("activeGoals", activeGoals);
            stats.put("completedGoals", completedGoals);

            return Result.success("获取成功", stats);
        } catch (Exception e) {
            return Result.error("获取统计信息失败: " + e.getMessage());
        }
    }
}
